import json

import pymysql
import requests

from quote_folder.Db_connect import DB_connect


class UpDateStatus:
    def __init__(self):
        self.url = "http://cpquery.cnipa.gov.cn/"
        self.bigdata_con = pymysql.connect(host="121.4.69.146", user='root', password='xhhg@2020', port=3306, db="big_data", use_unicode=True, charset='utf8')
        self.bigdata_cur = self.bigdata_con.cursor()
        self.kaifa = pymysql.connect(host='112.125.25.114', port=3306, user="python", password="pythonselect", database="mykhadmin")
        self.kaifa_cur = self.kaifa.cursor()

    def get_login(self):
        """获取登录token"""
        headers = {"Accept": "application/json"}
        url = 'https://api.xinhehonggu.com/api/auth/login'
        phone = '18866668888'
        password = 'xhhg2019'
        source = 'admin'
        data = {
            'method': '1',
            'phone': phone,
            'password': password,
            'source': source,
        }
        r = requests.post(url=url, data=data, headers=headers, verify=False)
        res_dict = r.json()
        token = res_dict['data']['token']
        return token

    def run(self):
        """主函数"""
        token = self.get_login()
        headers = {"Accept": "application/json"}
        url = "https://api.xinhehonggu.com/api/external_order/update"  # 系统外部订单更新接口
        # url = "http://test.api.whxhhgip.com/api/external_order/update"  # 测试接口
        self.get_content(url, token, headers)       # 获取案件专利信息，本地有数据有查询本地数据库，没有就网上爬  申请号在开发库的表external_orders
        self.bigdata_cur.close()
        self.bigdata_con.close()
        self.kaifa.close()
        self.kaifa_cur.close()

    def get_content(self, url, token, headers):
        select_sql = "SELECT * FROM `big_data`.`all_hospital_patent_date_TOTAL` WHERE `patent_user` LIKE '%湖北工程学院%'"
        self.bigdata_cur.execute(select_sql)
        data = self.bigdata_cur.fetchall()
        num = 997
        for i in data[997: len(data)]:
            print(f"当前正在处理{num}个专利")
            sqh = "CN" + i[1][0:12] + "." + i[1][-1]
            state = i[3]
            data = {
                'token': token,
                'secret': 'th45gdk1df5rdb51',
                "patentNo": sqh,  # 申请号
                'lawStatus': state  # 案件状态
            }
            # print(data)
            res = requests.put(url=url, headers=headers, data=data)
            jsondata = json.loads(res.text)
            print(jsondata, sqh, state)
            if jsondata['status'] == 'error' and jsondata['message'] == '专利号不存在':
                update_sql = f"UPDATE `all_hospital_patent_date_TOTAL` SET is_new = '1' WHERE sqh = '{i[1]}'"
                self.bigdata_cur.execute(update_sql)
                self.bigdata_con.commit()
                print('-' * 50 + '新增案件插入成功' + '-' * 50)
            num += 1


if __name__ == '__main__':
    uds = UpDateStatus
    uds().run()
#     2020207090033
